/**
 * 度°分′秒″转度
 * @param strDu
 * @param strFen
 * @param strMiao
 * @param len 精确到小数点后最多六位
 * @returns {number}
 */
function toDigital(strDu, strFen, strMiao, len) {
    len = (len > 6 || typeof (len) == "undefined") ? 6 : len;
    strDu = (typeof (strDu) == "undefined" || strDu === "") ? 0 : parseFloat(strDu);
    strFen = (typeof (strFen) == "undefined" || strFen === "") ? 0 : parseFloat(strFen) / 60;
    strMiao = (typeof (strMiao) == "undefined" || strMiao === "") ? 0 : parseFloat(strMiao) / 3600;
    var digital = strDu + strFen + strMiao;
    if (digital === 0) {
        return 0;
    } else {
        return parseFloat(digital.toFixed(len));
    }
}

/**
 * 度转度°分′秒″
 * @param val
 * @returns {string}
 */
function toDegrees(val) {
    val += ""
    if (typeof (val) == "undefined" || val === "") {
        return "";
    }
    var i = val.indexOf('.');
    var strDu = i < 0 ? val : val.substring(0, i);//获取度
    var strFen = 0;
    var strMiao = 0;
    if (i > 0) {
        strFen = "0" + val.substring(i);
        strFen = strFen * 60 + "";
        i = strFen.indexOf('.');
        if (i > 0) {
            strMiao = "0" + strFen.substring(i);
            strFen = strFen.substring(0, i);//获取分
            strMiao = strMiao * 60 + "";
            i = strMiao.indexOf('.');
            strMiao = strMiao.substring(0, i + 4);//取到小数点后面三位
            strMiao = parseFloat(strMiao).toFixed(2);//精确小数点后面两位
        } else {
            strMiao = "00.00";
        }
    } else {
        strFen = "00";
        strMiao = "00.00";
    }
    if (strFen.length === 1) strFen = "0" + strFen;
    let arr = strMiao.split('.');
    if (arr.length === 2 && arr[0].length === 1) {
        strMiao = "0" + strMiao;
    }
    return strDu + "°" + strFen + "'" + strMiao + "\"";

}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//每地图单位对应的距离
function getMeterPerMapUnit(mapUnit) {
    var earchRadiusInMeters = 6378137;
    var meterPerMapUnit;
    if (mapUnit == "METER") {
        meterPerMapUnit = 1;
    } else if (mapUnit == "DEGREE") {
        // 每度表示多少米。
        meterPerMapUnit = Math.PI * 2 * earchRadiusInMeters / 360;
    } else if (mapUnit == "KILOMETER") {
        meterPerMapUnit = 1.0E-3;
    } else if (mapUnit == "INCH") {
        meterPerMapUnit = 1 / 2.5399999918E-2;
    } else if (mapUnit == "FOOT") {
        meterPerMapUnit = 0.3048;
    }
    return meterPerMapUnit;
}

//resolution ： 一像素代表的地图单位
//scale : 地图比例尺最终形式为1:640000000 这样
function resolutionToScale(resolution, dpi, mapUnit) {
    var inchPerMeter = 1 / 0.0254;
    // 地球半径。
    var meterPerMapUnit = getMeterPerMapUnit(mapUnit);
    var scale = resolution * dpi * inchPerMeter * meterPerMapUnit;
    scale = 1 / scale;
    return scale;
}

//比例尺转换到屏幕分辨率
function scaleToResolution(scale, dpi, mapUnit) {
    var inchPerMeter = 1 / 0.0254;
    var meterPerMapUnitValue = getMeterPerMapUnit(mapUnit);
    var resolution = scale * dpi * inchPerMeter * meterPerMapUnitValue;
    resolution = 1 / resolution;
    return resolution;
}

function createOneBoatFeatureByStatus(status,isSelected) {
    var pointFeature = new ol.Feature(new ol.geom.Point([status.lng, status.lat]));
    pointFeature.setProperties({
        lng: status.lng,
        lat: status.lat,
        // name: point.name,
        angle: status.angle,
        code: status.code,
        type: featureType.boat
    });
    if(isSelected){
        pointFeature.setStyle(createBoatFeatureStyle(pointFeature,zoomLevel,true))
    }else{
        pointFeature.setStyle(createBoatFeatureStyle(pointFeature, zoomLevel));
    }
    return pointFeature;
}

function showBoatFeature(pointSource, map, statusList) {
    var pointLayer = new ol.layer.Vector({source: pointSource});
    for (let i = 0; i < statusList.length; i++) {
        pointSource.addFeature(createOneBoatFeatureByStatus(statusList[i]));
    }
    map.addLayer(pointLayer);
}

//当新来一个点位的时候更新
function updateBoatFeature(status) {
    //更新当前boat
    var features = boatPointSource.getFeatures();
    features.forEach(function (f) {
        if (f.getProperties().code === status.boatCode) {
            //先清理当前的
            boatPointSource.removeFeature(f);
            //再加入最新的
            boatPointSource.addFeature(createOneBoatFeatureByStatus(status));
            return;
        }
    })
}

function showAisFeature(aisSource, map, points) {
    var zoom = map.getView().getZoom();
    var aisLayer = new ol.layer.Vector({
        source: aisSource,
        title: "AIS_layer"
    });
    for (let i = 0; i < points.length; i++) {
        var point = points[i];
        var pointFeature = new ol.Feature(new ol.geom.Point([point.lng, point.lat]));
        if (point.type === featureType.boat) {
            //波浪艇
            pointFeature.setProperties({
                lng: point.lng,
                lat: point.lat,
                type: featureType.boat,
                angle: 90 //船舶给个默认值不然图标显示不出来
            });
            pointFeature.setStyle(createBoatFeatureStyle(pointFeature, zoom));
        } else {
            //AIS
            pointFeature.setProperties({
                lng: point.lng,
                lat: point.lat,
                type: featureType.AIS,
                speed: point.speed,
                angle: point.direction,
                mmsi: point.mmsi
            });
            pointFeature.setStyle(createAISFeatureStyle(pointFeature, zoom))
        }
        aisSource.addFeature(pointFeature);
    }
    map.addLayer(aisLayer);
}

function cleanAisFeature(aisSource, map) {
    aisSource.clear();
    map.getLayers().getArray().forEach(function (layer) {
        if (layer.get('title') === "AIS_layer") {
            map.removeLayer(layer);
            return true;
        }
    });
    map.render();
}

function changeBoatFeatureStyle(zoom) {
    boatPointSource.forEachFeature(function (feature) {
        var prop = feature.getProperties();
        if (selectedBoatFeature != null && selectedBoatFeature.getProperties().code === prop.code) {
            if (prop.type === featureType.boat) {
                feature.setStyle(createBoatFeatureStyle(feature, zoom, true));
            } else {
                feature.setStyle(createAISFeatureStyle(feature, zoom, true))
            }
        } else {
            if (prop.type === featureType.boat) {
                feature.setStyle(createBoatFeatureStyle(feature, zoom));
            } else if (prop.type === featureType.AIS) {
                feature.setStyle(createAISFeatureStyle(feature, zoom))
            }
        }
    });
}

//在zoomLevel<=boatIconChangedZoom 的时候是 圆点
//在zoomLevel > boatIconChangedZoom 的时候是带方向的三角
function createAISCanvas(zoom, selected) {
    var height, width;
    if (zoom > 4) {
        height = 48;
        width = 48;
    } else {
        height = 12;
        width = 12;
    }
    var canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    var ctx = canvas.getContext("2d");
    if (zoom > boatIconChangedZoom) {
        ctx.translate(width / 2, height / 2);
        // var rotationAngle = (angle * Math.PI) / 180;
        // ctx.rotate(rotationAngle);
        ctx.beginPath();
        ctx.moveTo(0, -1 * height / 2);
        ctx.lineTo(0, 0);
        ctx.closePath();
        ctx.strokeStyle = "#ff893b";
        ctx.stroke();

        ctx.beginPath();
        ctx.moveTo(0, 0);
        var y = height * Math.sin(15);
        var x = height * Math.sin(15) / 2;
        ctx.lineTo(-1 * x, y);
        ctx.lineTo(x, y);
        ctx.fillStyle = "#ff893b";
        ctx.fill();
    } else {
        ctx.fillStyle = "#ff893b";
        var radius = width / 2;
        ctx.beginPath();
        ctx.arc(width / 2, height / 2, radius, 0, 2 * Math.PI, true);
        ctx.fill();
    }
    return canvas;
}

//在zoomLevel<=boatIconChangedZoom 的时候是 圆点
//在zoomLevel > boatIconChangedZoom 的时候是带方向的三角
function createBoatCanvas() {
    var height = 12;
    var width = 12;
    var canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "#ffeb3b";
    var radius = width / 2;
    ctx.beginPath();
    ctx.arc(width / 2, height / 2, radius, 0, 2 * Math.PI, true);
    ctx.fill();
    return canvas;
}

function createBoatFeatureStyle(feature, zoom, selected) {
    var rotation = feature.getProperties().angle * Math.PI / 180;
    if (zoom <= boatIconChangedZoom) {
        var canvas = createBoatCanvas();
        return new ol.style.Style({
            image: new ol.style.Icon({
                img: canvas,
                imgSize: [canvas.width, canvas.height],
                rotation: rotation
            })
        });
    } else {
        /*var svgSrc = "/img/boat.svg";
        if ( rotation > Math.PI) {
            if (selected) {
                svgSrc = "/img/mirr_boat_selected.svg";
            } else {
                svgSrc = "/img/mirr_boat.svg";
            }
        } else {
            if (selected) {
                svgSrc = "/img/boat_selected.svg";
            }
        }
        return new ol.style.Style({
            image: new ol.style.Icon({
                src: svgSrc,
                imgSize: [48, 48],
                rotation: rotation
            }),
        });*/
        var svgSrc = "/img/boat.png";
        var style = new ol.style.Style({
            image: new ol.style.Icon({
                src: svgSrc,
                imageSize: [96, 96],
                rotation: rotation
            })
        });
        return style;
        /*if(selected){
            style.image
        }*/
    }
}

function createAISFeatureStyle(feature, zoom, selected) {
    var canvas = createAISCanvas(zoom, selected);
    return new ol.style.Style({
        image: new ol.style.Icon({
            img: canvas,
            imgSize: [canvas.width, canvas.height],
            rotation: feature.getProperties().angle * Math.PI / 180
        })
    });
}

/**
 * 生成uuid
 * @returns {string}
 */
function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}